package com.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 认证过滤器
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("AuthGlobalFilter 过滤器开始执行");
        ServerHttpRequest request = exchange.getRequest();

        // 1.前置白名单校验
//        if (isWhiteList(request.getPath().toString())) {
//            return chain.filter(exchange);
//        }

        // 2.认证校验
        //String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        String token = "token:111111122322";
        if (!StringUtils.hasText(token)) {
            log.warn("AuthGlobalFilter 请求未认证");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        Integer userId = parseToken(token);
        if (null == userId) {
            log.warn("AuthGlobalFilter 解析token异常");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 传递用户信息到其他服务
        ServerWebExchange webExchange = exchange.mutate()
                .request(builder -> builder.header("userId", userId.toString()))
                .build();
        return chain.filter(webExchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 2;
    }

    private boolean isWhiteList(String path) {
        return true;
    }

    private Integer parseToken(String token) {
        try {
            return 111111;
        } catch (Exception e) {
            return null;
        }
    }
}
